# Create your views here.
from datetime import datetime
from django.http import HttpResponseServerError
from Exams.forms import ExamForm, SaveExamDataToDb, saveStudentAnswers
from Exams.models import Exam, ExamUser, ExamQuestion, ExamOption, StudentExam
from Exams.models import ExamUser
from Exams.customfunctions import check_loginuser, calculate_grade, calculate_avgrade, calculate_order
from django.shortcuts import *
from django.contrib.auth.decorators import login_required
from pprint import pprint
from django.utils import simplejson
from django.views.decorators.csrf import csrf_exempt




@login_required
def index(request):
    check_loginuser(request.user.username) #from customfunctions
    student = ExamUser.objects.get(user_name = request.user.username)
    exams_all=Exam.objects.all()
    exams_open = Exam.objects.all().filter(deadline__gte=datetime.now()).exclude(studentexam__student=student.id).order_by('-deadline')
    exams_open.exclude(enabled=False)
    exams_taken=Exam.objects.all().filter(studentexam__student=student.id).order_by('-deadline')
    exams_closed = Exam.objects.all().filter(deadline__lte=datetime.now()).order_by('-deadline')

    #exams_closed.exclude(enabled=True)
    #exams_closed = Exam.objects.all().exclude(exams_open)
    exams = {"exams_open" : exams_open, "exams_taken":exams_taken ,"exams_closed" : exams_closed }
    objExams = {"exams" : exams}
    return render_to_response('exam/index.html', objExams, context_instance=RequestContext(request))
#

#only loggedin users can log out
@login_required
def logout(request):
    #forward to login site
    return render_to_response('registration/logged_out.html', context_instance=RequestContext(request))

@csrf_exempt
@login_required
def take(request, param_exam_id):
    if request.method == "POST":
        result = saveStudentAnswers(simplejson.loads(request.raw_post_data), request.user.username)
        return HttpResponse(simplejson.dumps({"success":result}), mimetype="application/json")
    else:
        usr = ExamUser.objects.all().get(user_name=request.user.username)
        exam = Exam.objects.get(pk = param_exam_id)
        questions = ExamQuestion.objects.all().filter(exam_id = exam.id)
        questionCount = questions.count()
        questionsObj = []
        for question in questions:
            options = ExamOption.objects.all().filter(exam_question_id = question.id)
            optionCount = options.count()
            questionsObj.append ( {"question" : question, "options":options, "qid":question.id, "optioncount":optionCount})
        formObj = {"exam" : exam, "questions": questionsObj, "questioncount":questionCount }
        return render_to_response('exam/take.html', formObj, context_instance=RequestContext(request))
    #try:
        #questions = Exam.objects.all().filter()
        #questions = ExamQuestion.objects.get(exam_id == param_exam_id)


        #for q in questions:
          #  options = ExamOption.objects.get(exam_question_id = q.id )
#        return HttpResponse(json.dumps(response_data), mimetype="application/json")

    #except Exam.DoesNotExist:
     #   raise Http404


@login_required
def show(request, param_exam_id):
    # get one exam by id and send to template
    try:
        exam = Exam.objects.get(pk=param_exam_id)
    except Exam.DoesNotExist:
        raise Http404
    return render_to_response('exam/show.html', {"exam" : exam}, context_instance=RequestContext(request))


@login_required
def statistics(request, param_exam_id):
    try:
        student = ExamUser.objects.get(user_name = request.user.username)
        grade = calculate_grade(student.id,param_exam_id )
        avg = calculate_avgrade(param_exam_id)
        (order, student_n) = calculate_order(student.id, param_exam_id)
        exam = Exam.objects.get(pk=param_exam_id)
        obj = {"exam":exam, "grade":grade, "average":avg, "order":order, "student_n":student_n}
    except Exam.DoesNotExist:
        raise Http404
    return render_to_response('exam/statistics.html', obj, context_instance=RequestContext(request))


@login_required
def edit(request):
    return render_to_response('exam/edit.html', context_instance=RequestContext(request))

#without inline test
@csrf_exempt
@login_required
def create(request):
    if request.method == "POST":
        exFrm = simplejson.loads(request.raw_post_data)
        success = SaveExamDataToDb(exFrm, request.user.username)
        return HttpResponse(simplejson.dumps({"success":success}), mimetype="application/json")
    else:
        return render_to_response('exam/create.html', context_instance=RequestContext(request))